<template>
  <el-dialog
    v-model="props.userDialog"
    title="编辑"
    width="30%"
    :show-close="false"
  >
    <el-form :model="ruleForm" :rules="rules" ref="accountFormRef">
      <el-form-item label="头像">
        <div class="headSculpture">
          <el-upload
            class="avatar-uploader"
            :action="`${proxy.$http}/user/upload/uploadFile`"
            :auto-upload="true"
            :http-request="(resp: any) => { return handleUpload(resp, 1) }"
            limit="1"
            :headers="headers"
            accept=".png,.jpg,jpeg"
            :show-file-list="false"
            :before-upload="(resp: any) => { return fileBeforeUpload(resp, 1) }"
            :on-error="(resp: any) => { return fileError(resp, 1) }"
            :disabled="true"
          >
            <img
              v-if="ruleForm.portrait"
              :src="ruleForm.portrait"
              class="avatar"
            />
            <div v-else class="picture">
              {{ realName }}
            </div>
          </el-upload>
          <div class="headBtn">
            <el-button class="btn" type="primary" plain @click="uploadHead"
              >上传头像</el-button
            >
            <div class="tips" style="margin: auto auto 0px 5px">
              只能上传jpg/png文件，且不超过1MB
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="姓名" prop="realName" class="login-animation2">
        <el-input
          v-model="ruleForm.realName"
          placeholder="请输入姓名"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex" class="login-animation2">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="手机号码"
        class="login-animation2"
        v-if="ruleForm.bindType == 2"
      >
        <el-input
          v-model="ruleForm.userTel"
          placeholder="请输入手机号码"
          style="width: 100%"
        />
        <div>提示：手机号将用于接收各类消息推送，请填写常用手机号</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quxiao(accountFormRef)">取消</el-button>
        <el-button
          type="primary"
          @click="queren(accountFormRef)"
          :loadding="loadding"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElLoading, FormInstance, FormRules } from 'element-plus'
import { ref, reactive, getCurrentInstance, watch } from 'vue'
import { Session } from '/@/utils/storage'
import { updateLoginUserInfoApi } from '/@/api/user'
import { uploadFileApi } from '/@/api/publicApi'
const { proxy } = getCurrentInstance() as any
const props = defineProps({
  userDialog: Boolean,
  userFormUpadate: Object
})
const emit = defineEmits(['quxiaoUser', 'qrUser'])
const accountFormRef = ref<FormInstance>()
const loadding = ref(false)
const realName = ref('')
const ruleForm = ref({
  realName: '',
  sex: '',
  portrait: '',
  userTel: '',
  bindType: 0
})
const rules = reactive<FormRules>({
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
})

const quxiao = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emit('quxiaoUser')
}
const queren = async (formEl: FormInstance | undefined) => {
  loadding.value = true
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      updateLoginUserInfoApi(ruleForm.value).then((res) => {
        if (res.code == 0) {
          ElMessage.success('修改成功')
          loadding.value = false
          emit('qrUser')
        } else {
          loadding.value = false
        }
      })
    } else {
      loadding.value = false
    }
  })
}

//头像上传
const userInfo = Session.get('token')
const token = userInfo ? userInfo : ''
const headers = ref({
  'Content-Type': 'multipart/form-data',
  'Api-User-Token': token
})
const handleUpload = (file: any, type: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '上传中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  uploadFileApi({ type: 1, file: file.file }).then((res: any) => {
    if (res.code == 0) {
      ruleForm.value.portrait = res.data.fileIds[0]
      loading.close()
    } else {
      loading.close()
    }
  })
}

const fileError = (err: any, type: any) => {
  ElMessage.error('项目文件上传失败！')
  ruleForm.value.portrait = ''
}
const fileBeforeUpload = (rawFile: any, type: any) => {
  // console.log('rawFile', rawFile)
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('请上传jpg/png文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('上传文件不能超过1MB!')
    return false
  }
  return true
}

const uploadHead = () => {
  const fileType = ['jpg', 'png']
  const inputFile = document.createElement('input') as any
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.click()
  inputFile.addEventListener('change', () => {
    const file = inputFile.files[0]
    var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)

    if (!fileType.includes(testmsg)) {
      ElMessage.warning('上传的文件格式只能是,jpg,png')
      document.body.removeChild(inputFile)
      return false
    }
    //上传接口
    handleUpload({ file: file }, 1)
  })
}

watch(
  () => props.userDialog,
  () => {
    if (props.userDialog == true) {
      ruleForm.value.portrait = props.userFormUpadate?.portrait
      ruleForm.value.userTel = props.userFormUpadate?.userTel
      ruleForm.value.sex = props.userFormUpadate?.sex
      ruleForm.value.realName = props.userFormUpadate?.realName
      ruleForm.value.bindType = props.userFormUpadate?.bindType
      realName.value = props.userFormUpadate?.realName.slice(0, 1)
    }
  }
)
</script>
<style scoped lang="scss">
.tips {
  text-align: center;
  margin-bottom: 15px;
  font-size: var(--el-font-size-base);
}

.headSculpture {
  display: flex;

  .headBtn {
    margin-left: 24px;

    .btn {
      margin-bottom: 24px;
    }

    .tips {
      font-size: 12px;
      font-weight: 400;
      line-height: 20px;
      color: rgba(140, 140, 140, 1);
      text-align: left;
    }
  }
}

.avatar-uploader .avatar {
  width: 72px;
  height: 72px;
  display: block;
}

.picture {
  font-size: 36px;
  line-height: 72px;
  color: #ffffff;
  width: 72px;
  height: 72px;
  text-align: center;
  background: var(--el-color-primary);
}
</style>
